package shutdownhook;

import java.io.File;
import java.io.IOException;

public class Demo2 {

    public static void main(String[] args) {

        Demo2 demo2 = new Demo2();
        demo2.initial();
        String fileName = "test.txt";
        try {
            demo2.createFile(fileName);
            System.out.println(demo2.file.getCanonicalPath());
            System.out.println("创建了文件[" + fileName + "]");
            System.out.println("按任意键退出");
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    File file = null;

    void initial() {
        Runtime.getRuntime().addShutdownHook(new Shutdown());
    }
    private void createFile(String fileName) throws IOException {
        File file = new File(System.getProperty("user.dir"), fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        this.file = file;
    }

    private void deleteFile() {
        if (file.exists()) {
            file.delete();
            System.out.println("删除了文件");
        }
    }

    private class Shutdown extends Thread {
        @Override
        public void run() {
            deleteFile();
        }
    }
}
